<template>
  <div class="container">
    <input type="file" ref="excelRef" :accept="props.accept" @change="onChangeFile"  class="excel" style="display: none;"/>
    <div>  {{ fileName }}  <van-button  type="primary" size="small" @click="openFile">浏览文件</van-button></div>  
    <van-button round type="success" size="small" @click="onChange">上传文件</van-button>
    <h2>解析数据：</h2>

    <van-list>
      <van-cell-group inset class="container-item"  v-for="(item,index) in excelData" :key="index">
        <van-cell>
          {{item.name}} {{item.age}} {{item.skill}} {{item.telephone}}
        </van-cell>
      </van-cell-group>
    </van-list>

  </div>
</template>
  
<script  lang="ts" setup> 
import { ref,getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx' 

const { proxy }: any = getCurrentInstance();//关键代码
const props = defineProps({
  accept: { type: String, default: '.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }
});

const fileName=ref<string>('请上传excel文件') 
const excelRef: any = ref(null);
const excelData = ref<any[]>([]);

const excelNameToKey:any = {
  姓名 : "name",
  年龄 : "age", 
  特长 : "skill",
  电话 : "telephone", 
  地址 : "address", 
};
// 标准化 JSON 数据
const excelDataToJson = (sheetJson: any[]) => {
  if (!sheetJson.length) return;
  let result = sheetJson;  
  excelData.value = [];
  // const hasTableHead = !!sheetJson[0].__EMPTY; //是否有表头 
  // 将表格对应的文字转换为 key
  result.forEach((item) => { 
    const newItem: any = {};
    Object.keys(item).forEach((key) => {  
      newItem.title = key; 
      newItem[excelNameToKey[key]] = item[key];
    });
    excelData.value.push(newItem);
  }); 
};
 
// 读取对应表格文件
const readerExcel = (file: File) => {
  const fileReader = new FileReader();
  // 以二进制的方式读取表格内容
  fileReader.readAsBinaryString(file);
  // 表格内容读取完成
  fileReader.onload = (event: any) => {
    try {
      const fileData = event.target.result;
      const workbook = XLSX.read(fileData, {
        type: "binary",
      });
      // 表格是有序列表，因此可以取多个 Sheet，这里取第一个 Sheet
      const wsname = workbook.SheetNames[0];
      // 将表格内容生成 json 数据
      const sheetJson = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
      excelData.value = sheetJson; 
      excelDataToJson(sheetJson);
    } catch (e) {
      console.log(e);
      return false;
    }
  };
};

const openFile = (event: any) => {
  excelRef.value.click();   
};

const onChangeFile = (event: any) => {
  proxy.$modal.loading(); 
  const file =event.target.files&&event.target.files[0]; 
  if(file){
    fileName.value=file.name;
  }   
  setTimeout(() => {
    proxy.$modal.closeLoading(); 
  }, 200); 
}; 
// 文件变化时触发
const onChange = (event: any) => { 
  // 获取文件对象
  //const file = event.target.files[0];
  const file = excelRef.value.files[0];
  if(!file){
    proxy.$modal.notifyWarning("请先上传Excel表格"); 
    return;
  }
  //console.log('file===================>', file)
  // 读取文件内容
  readerExcel(file);
  // 清除数据
  clearFile();
};
const clearFile = () => {
  excelRef.value.value = "";
};
</script>


<style lang="scss" scoped>
.container {
  padding: 20px 15px;

  &-item {
    margin: 10px 0px;
  } 
}
 
.van-button__content {
  background-color: blue;
}
</style>
